package chapter12.eg2;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class LoginAuthRespHandler extends SimpleChannelInboundHandler<NettyMessage> {

  private Map<String, Boolean> nodeCheck = new ConcurrentHashMap<>();
  private String[] whiteList = {"127.0.0.1"};

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, NettyMessage message) throws Exception {
    if (message.getHeader() != null
      && message.getHeader().getType() == MessageType.LOGIN_REQ.value()) {
      String nodeIndex = ctx.channel().remoteAddress().toString();
      NettyMessage loginResp = null;
      if (nodeCheck.containsKey(nodeIndex)) {
        loginResp = buildResponse((byte) -1);
      } else {
        InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
        String ip = address.getAddress().getHostAddress();
        boolean isOK = Arrays.asList(whiteList).contains(ip);
        loginResp = isOK ? buildResponse((byte) 0) : buildResponse((byte) -1);
        if (isOK) {
          nodeCheck.put(nodeIndex, true);
        }

        System.out.println("The login response is: " + loginResp + ", body [" + loginResp.getBody() + "]");
        ctx.writeAndFlush(loginResp);
      }
    } else {
      ctx.fireChannelRead(message);
    }
  }

  private NettyMessage buildResponse(byte result) {
    NettyMessage message = new NettyMessage();
    Header header = new Header();
    header.setType(MessageType.LOGIN_RESP.value());
    message.setHeader(header);
    message.setBody(result);
    return message;
  }
}
